#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <sys/wait.h>

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
    {
        std::cerr << "pipe" << std::endl;
        exit(1);
    }
    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "id" << std::endl;
        exit(1);
    }
    else if (id == 0)
    {
        close(pipefd[0]);
        int count = 10;
        while (count--)
        {
            std::string s;
            s += "hahaha" + std::to_string(count) + " ";
            write(pipefd[1], s.c_str(), s.size());
            sleep(1);
        }
        close(pipefd[1]);
        std::cout << "写端关闭" << std::endl;
        exit(0);
    }
    else
    {
        close(pipefd[1]);
        char buffer[1024];
        while (true)
        {
            // close(pipefd[0]);
            // sleep(5);
            ssize_t n = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                std::cout << "读到数据: " << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "return val : " << n << std::endl;
                sleep(1);
            }
            else
            {
                std::cout << "read error" << std::endl;
                sleep(1);
            }
            // break;
            sleep(1);
            // printf("有bug\n");
            // printf("%s\n", buffer);
        }
    }
    close(pipefd[0]);
    std::cout << "读端关闭" << std::endl;

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid > 0)
    {
        int exitcode = (status >> 8) & 0xFF;
        int exitsig = (status & 0x7F); // 13
        std::cout << "wait success, rid: " << rid << ", exit code: " << exitcode << ", exitsig: " << exitsig << std::endl;
    }
    return 0;
}